#include "rasterwidget.h"
#include <iostream>
#include <QPainter>
#include <QResizeEvent>
#include <QImage>

using mathengine::Vec2f;

static constexpr int kDefaultWidth  = 800;
static constexpr int kDefaultHeight = 800;

RasterWidget::RasterWidget(QWidget *parent)
    : QWidget(parent), image_(QImage(kDefaultWidth, kDefaultHeight, QImage::Format_ARGB32)),
    rasterizer_(kDefaultWidth, kDefaultHeight, image_) {
    this->setStyleSheet("border: none; background: white;");
    this->setWindowFlags(Qt::FramelessWindowHint); // hide border and title
    this->setWindowFlags(Qt::NoDropShadowWindowHint); // hide shadow
    this->setAttribute(Qt::WA_TranslucentBackground);
    this->setAttribute(Qt::WA_NoSystemBackground);
}

void RasterWidget::render(std::function<void(void)> &callback) {
    rasterizer_.clear(raster::kBlackColor);
    rasterizer_.drawScene();
    callback();
    update();
}

std::vector<float> RasterWidget::eyePos() {
    auto pos = rasterizer_.eyePos();
    return { pos.x(), pos.y(), pos.z() };
}

std::vector<float> RasterWidget::lightDir() {
    auto dir = rasterizer_.lightDir();
    return { dir.x(), dir.y(), dir.z() };
}

void RasterWidget::setEyePos(std::vector<float> pos) {
    rasterizer_.setEyePos({ pos[0], pos[1], pos[2] });
}

void RasterWidget::setLightDir(std::vector<float> dir) {
    rasterizer_.setLightDir({ dir[0], dir[1], dir[2] });
}

void RasterWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.drawImage(0, 0, image_);
}

void RasterWidget::resizeEvent(QResizeEvent *event) {
    QWidget::resizeEvent(event);

    QSize size = event->size();
    if (!image_.isNull()) {
        // image_ = image_.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
        // rasterizer_.viewport(0, 0, image_.width(), image_.height());
    }

    update(); // triggle repaint

    qDebug() << "resizeEvent, size: " << QString("%1x%2").arg(width()).arg(height());
    emit sizeChanged();
}

void RasterWidget::mousePressEvent(QMouseEvent *event) {
    std::cout << "mousePressEvent" << std::endl;
}

void RasterWidget::mouseMoveEvent(QMouseEvent *event) {

}
